pip install yfinanceimport pandas as pdimport yfinance as yffrom datetime import datetimeimport plotly.express as pxx
start_date = datetime.now() - pd.DateOffset(months=60)end_date = datetime.now()tickers = ['AAPL', 'MSFT']df_list = []for ticker in tickers: data = yf.download(ticker, start=start_date, end=end_date) df_list.append(data)df = pd.concat(df_list, keys=tickers, names=['Ticker', 'Date'])print(df.head())x
df = df.reset_index()print(df.head())x
fig = px.line(df, x='Date', y='Close', color='Ticker', title="Stock Market Performance for the Last 60 Months")fig.show()x
fig = px.area(df, x='Date', y='Close', color='Ticker', facet_col='Ticker', labels={'Date':'Date', 'Close':'Closing Price', 'Ticker':'Company'}, title='Stock Prices for Apple, Microsoft')fig.show()df['MA10'] = df.groupby('Ticker')['Close'].rolling(window=10).mean().reset_index(0, drop=True)df['MA20'] = df.groupby('Ticker')['Close'].rolling(window=20).mean().reset_index(0, drop=True)for ticker, group in df.groupby('Ticker'): print(f'Moving Averages for {ticker}') print(group[['MA10', 'MA20']])for ticker, group in df.groupby('Ticker'): fig = px.line(group, x='Date', y=['Close', 'MA10', 'MA20'], title=f"{ticker} Moving Averages") fig.show()# create a DataFrame with the stock prices of Apple and Microsoftapple = df.loc[df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'AAPL'})microsoft = df.loc[df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'MSFT'})df_corr = pd.merge(apple, microsoft, on='Date')# create a scatter plot to visualize the correlationfig = px.scatter(df_corr, x='AAPL', y='MSFT', trendline='ols', title='Correlation between Apple and Microsoft')fig.show()import pandas as pdimport plotly.express as pximport numpy as np# Assuming df is your DataFrame containing stock prices# Replace df with your actual DataFrame containing the data# create a DataFrame with the stock prices of Apple and Microsoftapple = df.loc[df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'AAPL'})microsoft = df.loc[df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'MSFT'})df_corr = pd.merge(apple, microsoft, on='Date')# create a scatter plot to visualize the correlationfig = px.scatter(df_corr, x='AAPL', y='MSFT', trendline='ols', title='Correlation between Apple and Microsoft')# Calculate correlation coefficientcorrelation_coefficient = np.corrcoef(df_corr['AAPL'], df_corr['MSFT'])[0, 1]correlation_text = f'Correlation coefficient: {correlation_coefficient:.2f}'# Add correlation text as annotationfig.add_annotation( x=0.5, y=0.9, xanchor='center', yanchor='top', text=correlation_text, showarrow=False, font=dict(size=12, color='black'),)fig.show()import pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_score, mean_squared_errorimport matplotlib.pyplot as plt# Assuming df is your DataFrame containing stock prices# Replace df with your actual DataFrame containing the data# create a DataFrame with the stock prices of Apple and Microsoftapple = df.loc[df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'AAPL'})microsoft = df.loc[df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'MSFT'})df_regression = pd.merge(apple, microsoft, on='Date')# Selecting the features (independent variables) and the target (dependent variable)X = df_regression[['AAPL']]y = df_regression['MSFT']# Splitting the data into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# Creating and training the linear regression modelmodel = LinearRegression()model.fit(X_train, y_train)# Making predictionsy_pred_train = model.predict(X_train)y_pred_test = model.predict(X_test)# Calculate R-squared valuer2_train = r2_score(y_train, y_pred_train)r2_test = r2_score(y_test, y_pred_test)# Calculate mean squared errormse_train = mean_squared_error(y_train, y_pred_train)mse_test = mean_squared_error(y_test, y_pred_test)# Plotting the actual vs. predicted valuesplt.figure(figsize=(10, 6))plt.scatter(X_test, y_test, color='blue', label='Actual')plt.plot(X_test, y_pred_test, color='red', linewidth=2, label='Predicted')plt.title('Actual vs. Predicted Stock Prices (Testing Data)')plt.xlabel('AAPL Stock Price')plt.ylabel('MSFT Stock Price')plt.legend()plt.grid(True)plt.show()print(f'R-squared (Training): {r2_train:.2f}')print(f'R-squared (Testing): {r2_test:.2f}')print(f'Mean Squared Error (Training): {mse_train:.2f}')print(f'Mean Squared Error (Testing): {mse_test:.2f}')